﻿using ChatCommon;
using ChatCommon.Packets;
using Lidgren.Network;
using NetBrick.Server;

namespace ChatServer
{
    public class ChatPeer : BasePeer
    {
        public bool Authenticated { get; private set; }
        public string Username { get; private set; }

        public ChatPeer(NetConnection connection) : base(connection)
        {
            Authenticated = false;
        }

        public override void OnConnect()
        {
            Log.Info("An unauthenticated user connected.");
        }

        public void Authenticate(string username)
        {
            Authenticated = true;
            Username = username;
            Log.Info("User {0} joined.", Username);
            var chatPacket = new ChatPacket.Event("Server", "Player " + Username + " joined.");
            Program.ChatServer.BroadcastPacket(ChatPacketCode.ChatMessageEvent, chatPacket, NetDeliveryMethod.ReliableOrdered);
        }

        public override void OnDisconnect(string reason)
        {
            if (Authenticated)
            {
                Log.Info("User {0} left. Reason: {1}", Username, reason);
                var chatPacket = new ChatPacket.Event("Server", "Player " + Username + " left.");
                Program.ChatServer.BroadcastPacket(ChatPacketCode.ChatMessageEvent, chatPacket, NetDeliveryMethod.ReliableOrdered);
            }
            else
            {
                Log.Info("An unauthenticated user disconnected.");
            }
        }
    }
}